﻿using System;
using System.Threading.Tasks;

namespace Yz.Core.Tools
{
    public class YzTask
    {
        /// <summary>
        ///     在线程上执行指定工作队列并捕获异常
        /// </summary>
        /// <param name="action"></param>
        public static Task TaskRun(Action action)
        {
            var theTask = Task.Run(action);
            theTask.ContinueWith(task =>
            {
                foreach (var ex in task.Exception.InnerExceptions)
                {
                    YzNLog.Error(ex);
                }
            }, TaskContinuationOptions.OnlyOnFaulted);
            return theTask;
        }

        /// <summary>
        ///     在线程上执行指定工作队列并返回结果（捕获异常）
        /// </summary>
        /// <param name="action"></param>
        public static Task<TResult> TaskRun<TResult>(Func<TResult> function)
        {
            var theTask = Task.Run(function);
            theTask.ContinueWith(task =>
            {
                foreach (var ex in task.Exception.InnerExceptions)
                {
                    YzNLog.Error(ex);
                }
            }, TaskContinuationOptions.OnlyOnFaulted);
            return theTask;
        }
    }
}